/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets.content.thumbnailers;

import com.codemagi.servlets.AppException;
import com.codemagi.servlets.content.ThumbnailController;
import com.codemagi.util.*;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.media.jai.*;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;

/**
 * This class implements IThumbnailer to display a 16x16 icon for the selected file type. 
 *
 * The icons to use should be placed in the WEB-INF/etc/icons directory.
 * 
 * If no icon exists for a particular file extension, a default thumbnail will be used.
 */
public class IconThumbnailer implements com.codemagi.servlets.content.thumbnailers.IThumbnailer {

    Logger log = Logger.getLogger(this.getClass());

    //members
    ServletContext application;

    //GETTERS AND SETTERS ------------------------

    public void setApplication(ServletContext newValue) {
	application = newValue;
    }

    public void createThumbnail(String sourceFile, String thumbFile, int targetWidth, int targetHeight, boolean doOverlay)
        throws AppException {

	String thumbDir = sourceFile.substring(0, sourceFile.lastIndexOf("/") + 1) + ThumbnailController.THUMBS_DIRECTORY + "/" ;
        log.debug("**** createThumbnail(" + sourceFile + ", " + thumbDir + ", " + thumbFile + ")");

	String extension = sourceFile.substring(sourceFile.lastIndexOf(".") + 1);
	extension = StringUtils.toLowerCase(extension);
	log.debug("rendering for extension=" + extension);

	URL iconUrl = null;
	try {
	    iconUrl = application.getResource("/WEB-INF/etc/icons/icon_" + extension + ".png");
	    log.debug("iconUrl: " + iconUrl);

	    if (iconUrl == null) iconUrl = application.getResource("/WEB-INF/etc/icons/icon_unknown.png");

	} catch (java.net.MalformedURLException e) {
	    log.debug("Unable to load icon", e);
	    return;
	}

	try {
	    RenderedOp source         = JAI.create("url", iconUrl);

	    log.debug("source="+source);

	    //scale the image
	    source = ThumbnailController.scaleImage(source, targetWidth, targetHeight);

	    //create the output directory if needed                                                                 
            java.io.File outDir = new File(thumbDir);
            outDir.mkdirs();

	    //save the image to the filesystem                                                             
            log.debug("ABOUT TO CREATE: source: " + source + " thumbFile: " + thumbFile);
            JAI.create("filestore", source, thumbFile, "png");

        } catch (Exception e) {
            log.debug("", e);
            throw new AppException(ThumbnailController.MSG_THUMBNAIL_ERROR);

        } catch (Throwable t) {
            log.debug("", t);
            throw new AppException(ThumbnailController.MSG_THUMBNAIL_ERROR);

        }
    }


    public Dimension getDimension(String sourceFile) throws AppException {

        RenderedOp image = null;
        try {
            image = ImageUtils.loadImage(sourceFile);
        } catch (IOException ioe) {
            throw new AppException("error loading image");
        }
        return new Dimension( image.getWidth(), image.getHeight() );
    }

}
